package engine;

import java.util.List;

import primitives.Box;
import primitives.Patch;
import primitives.Room;
import primitives.Shape;
import utility.Intersection;
import utility.Vector3;

public class RayCaster {

	private final int DEPTH = 600;
	private final double BACKGROUND_COLOR = 0.65;
	
	public Intersection<Patch, Double> castRay(Vector3 eyePosition, Vector3 pixel, List<Shape> shapes) {
		Intersection<Patch, Double> closestIntersection = null;
		double closestT = Double.POSITIVE_INFINITY;
		for(Shape shape : shapes) {
			Intersection<Patch,Double> result = shape.intersects(eyePosition, pixel);
			if(!Double.isNaN(result.t) && result.t < closestT && result.t > 0){
				closestT = result.t;
				closestIntersection = result;
			}
		}
		return closestIntersection;
	}
	
	public double[][] run(List<Shape> shapes, int width, int height) {
		double[][] pixels = new double[width][height];
		Vector3 eyePosition = new Vector3(new double[]{0, 0, 1000});
		Box room = (Box)shapes.get(0);
		for(Shape shape : shapes) {
			if(shape instanceof Room) {
				room = (Room) shape;
			}
		}
		Patch p0 = room.patches.get(0);
		Patch p1 = room.patches.get(1);
		room.patches.remove(p0);
		room.patches.remove(p1);
		for(int x = 0; x < pixels.length; x++) {
			for(int y = 0; y < pixels[x].length; y++) {
				Vector3 pixel = new Vector3(new double[]{
						x - width / 2, y - width / 2, DEPTH});
				Intersection<Patch,Double> closest = castRay(eyePosition, pixel, shapes);
				pixels[x][pixels[x].length - y - 1] = (closest == null) ? BACKGROUND_COLOR :
					closest.patch.excident;
			}
		}
		room.patches.add(0, p1);
		room.patches.add(0, p0);
		return pixels;
	}
	
	public void setColor(Patch patch) {
		if(patch.children == null) {
			patch.excident = 0;
		} else {
			for(Patch child : patch.children) {
				setColor(child);
			}
		}
	}
	
	
}
